package me.firstapp.manage.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.manage.utils.BizData4Page;
import me.firstapp.manage.utils.OpenApiUtils;
import me.firstapp.module.weixin.member.PaymentRecord;
import me.firstapp.module.weixin.order.ProductOrder;
import me.firstapp.module.weixin.order.SoftOrder;
import me.firstapp.service.weixin.pay.PaymentRecordService;
import me.firstapp.service.weixin.product.ProductOrderService;
import me.firstapp.service.weixin.soft.SoftOrderService;

@Controller
@RequestMapping(value = "/orderManage")
public class OrderManageAct extends BaseManage {

	@Autowired
	private SoftOrderService softOrderService;

	@Autowired
	private PaymentRecordService paymentRecordService;

	@Autowired
	private ProductOrderService productOrderService;

	@Autowired
	private RestTemplate restTemplate;


	@ResponseBody
	@RequestMapping(value = "/findSoftOrderPage.do", method = RequestMethod.POST)
	public void findSoftOrderPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<Object>();
		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			String startTime = null;
			String endTime = null;
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						if ("createTime".equals(key)) {
							// 日期范围判断
							String registerTimes = (String) jsonObject.get(key);
							if (registerTimes.contains(",")) {
								String[] registerTimesArra = registerTimes.split(",");
								startTime = registerTimesArra[0];
								endTime = registerTimesArra[1];
								if ("0".equals(startTime)) {
									startTime = null;
								}
								if ("0".equals(endTime)) {
									endTime = null;
								}
							}
						} else {
							searchParams.put(key, jsonObject.get(key));
						}
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				Page<SoftOrder> orderPage = softOrderService.findSoftOrderPage(pageNo, iDisplayLength, searchParams,
						mDataProp, sSortDir_0,
						StrUtils.isNULL(startTime) ? null : DateUtils.getDateFromTimeStamp(startTime, "yyyy-MM-dd"),
						StrUtils.isNULL(endTime) ? null : DateUtils.getDateFromTimeStamp(endTime, "yyyy-MM-dd"));

				BizData4Page<SoftOrder> bizData4Page = new BizData4Page<SoftOrder>();
				bizData4Page.setUserdata(conditions);
				if (orderPage != null) {
					bizData4Page.setPage(orderPage.getPageNo());
					bizData4Page.setPagesize(orderPage.getPageSize());
					bizData4Page.setRecords(orderPage.getEntityCount());
					bizData4Page.setRows(new ArrayList<SoftOrder>(orderPage.getEntities()));
					bizData4Page.setTotal(orderPage.getEntityCount());
				}

				result.setObject(bizData4Page);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/addSoftOrderRemark.do", method = RequestMethod.POST)
	public void addSoftOrderRemark(String orderNo, String remark, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			SoftOrder softOrder = softOrderService.findByOrderNo(orderNo);
			softOrder.setRemark(remark);
			softOrderService.executeUpdate(softOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/completeSoftOrder.do", method = RequestMethod.POST)
	public void completeSoftOrder(String orderNo, String remark, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			SoftOrder softOrder = softOrderService.findByOrderNo(orderNo);
			softOrderService.executeCompleteOrder(softOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@ResponseBody
	@RequestMapping(value = "/findPaymentRecordPage.do", method = RequestMethod.POST)
	public void findPaymentRecordPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<Object>();
		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			String startTime = null;
			String endTime = null;
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						if ("payTime".equals(key)) {
							// 日期范围判断
							String registerTimes = (String) jsonObject.get(key);
							if (registerTimes.contains(",")) {
								String[] registerTimesArra = registerTimes.split(",");
								startTime = registerTimesArra[0];
								endTime = registerTimesArra[1];
								if ("0".equals(startTime)) {
									startTime = null;
								}
								if ("0".equals(endTime)) {
									endTime = null;
								}
							}
						} else {
							searchParams.put(key, jsonObject.get(key));
						}
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				Page<PaymentRecord> paymentRecordPage = paymentRecordService.findPaymentRecordPage(pageNo,
						iDisplayLength, searchParams, mDataProp, sSortDir_0,
						StrUtils.isNULL(startTime) ? null : DateUtils.getDateFromTimeStamp(startTime, "yyyy-MM-dd"),
						StrUtils.isNULL(endTime) ? null : DateUtils.getDateFromTimeStamp(endTime, "yyyy-MM-dd"));

				BizData4Page<PaymentRecord> bizData4Page = new BizData4Page<PaymentRecord>();
				bizData4Page.setUserdata(conditions);
				if (paymentRecordPage != null) {
					bizData4Page.setPage(paymentRecordPage.getPageNo());
					bizData4Page.setPagesize(paymentRecordPage.getPageSize());
					bizData4Page.setRecords(paymentRecordPage.getEntityCount());
					bizData4Page.setRows(new ArrayList<PaymentRecord>(paymentRecordPage.getEntities()));
					bizData4Page.setTotal(paymentRecordPage.getEntityCount());
				}

				result.setObject(bizData4Page);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@ResponseBody
	@RequestMapping(value = "/findProductOrderPage.do", method = RequestMethod.POST)
	public void findProductOrderPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<Object>();
		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			String startTime = null;
			String endTime = null;
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						if ("createTime".equals(key)) {
							// 日期范围判断
							String registerTimes = (String) jsonObject.get(key);
							if (registerTimes.contains(",")) {
								String[] registerTimesArra = registerTimes.split(",");
								startTime = registerTimesArra[0];
								endTime = registerTimesArra[1];
								if ("0".equals(startTime)) {
									startTime = null;
								}
								if ("0".equals(endTime)) {
									endTime = null;
								}
							}
						} else {
							searchParams.put(key, jsonObject.get(key));
						}
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				Page<ProductOrder> orderPage = productOrderService.findProductOrderPage(pageNo, iDisplayLength,
						searchParams, mDataProp, sSortDir_0,
						StrUtils.isNULL(startTime) ? null : DateUtils.getDateFromTimeStamp(startTime, "yyyy-MM-dd"),
						StrUtils.isNULL(endTime) ? null : DateUtils.getDateFromTimeStamp(endTime, "yyyy-MM-dd"));

				BizData4Page<ProductOrder> bizData4Page = new BizData4Page<ProductOrder>();
				bizData4Page.setUserdata(conditions);
				if (orderPage != null) {
					bizData4Page.setPage(orderPage.getPageNo());
					bizData4Page.setPagesize(orderPage.getPageSize());
					bizData4Page.setRecords(orderPage.getEntityCount());
					bizData4Page.setRows(new ArrayList<ProductOrder>(orderPage.getEntities()));
					bizData4Page.setTotal(orderPage.getEntityCount());
				}

				result.setObject(bizData4Page);
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/sendProductOrder.do", method = RequestMethod.POST)
	public void sendProductOrder(String orderNo, String freightName, String freightNo, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			ProductOrder productOrder = productOrderService.findByOrderNo(orderNo);
			if (null == productOrder) {
				throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
			}
			if (ProductOrder.STATUS_PAYED != productOrder.getStatus()) {
				throw new ServiceException("error", "订单不是已支付状态");
			}
			productOrder.setFreightName(freightName);
			productOrder.setFreightNo(freightNo);
			productOrder.setStatus(ProductOrder.STATUS_COMPLETE);
			productOrder.setCompleteTime(new Date());
			productOrderService.executeUpdate(productOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			// 通知发货
			try {
				OpenApiUtils.sendOrderMsg(restTemplate, orderNo);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/returnProductOrder.do", method = RequestMethod.POST)
	public void returnProductOrder(String orderNo, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			ProductOrder productOrder = productOrderService.findByOrderNo(orderNo);
			if (null == productOrder) {
				throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
			}
			if (ProductOrder.STATUS_COMPLETE != productOrder.getStatus()
					&& ProductOrder.STATUS_PAYED != productOrder.getStatus()) {
				throw new ServiceException("error", "订单不是已支付或已完成状态");
			}
			productOrderService.executeReturn(productOrder);
			try {
				OpenApiUtils.returnOrderMsg(restTemplate, orderNo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/editProductOrder.do", method = RequestMethod.POST)
	public void editProductOrder(String orderNo, String receiveName, String receiveMobile, String receiveAddress,
			String outSysName, String outOrderNo, String freightName, String freightNo, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			ProductOrder productOrder = productOrderService.findByOrderNo(orderNo);
			if (null == productOrder) {
				throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
			}
			if (ProductOrder.STATUS_COMPLETE == productOrder.getStatus()) {
				throw new ServiceException("error", "订单已完成");
			}
			if (ProductOrder.STATUS_RETURN == productOrder.getStatus()) {
				throw new ServiceException("error", "订单已退货");
			}
			if (ProductOrder.STATUS_CANCEL == productOrder.getStatus()) {
				throw new ServiceException("error", "订单已取消");
			}
			if (StrUtils.isNotNULL(receiveName)) {
				productOrder.setReceiveName(receiveName);
			}
			if (StrUtils.isNotNULL(receiveMobile)) {
				productOrder.setReceiveMobile(receiveMobile);
			}
			if (StrUtils.isNotNULL(receiveAddress)) {
				productOrder.setReceiveAddress(receiveAddress);
			}
			if (StrUtils.isNotNULL(outSysName)) {
				productOrder.setOutSysName(outSysName);
			}
			if (StrUtils.isNotNULL(outOrderNo)) {
				productOrder.setOutOrderNo(outOrderNo);
			}
			if (StrUtils.isNotNULL(freightName)) {
				productOrder.setFreightName(freightName);
			}
			if (StrUtils.isNotNULL(freightNo)) {
				productOrder.setFreightNo(freightNo);
			}
			productOrderService.executeUpdate(productOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/remarkProductOrder.do", method = RequestMethod.POST)
	public void remarkProductOrder(String orderNo, String sysRemark, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			ProductOrder productOrder = productOrderService.findByOrderNo(orderNo);
			if (null == productOrder) {
				throw new ServiceException(StatusHouse.STATUS_ORDER_NOT_EXIST);
			}
			productOrder.setSysRemark(sysRemark);
			productOrderService.executeUpdate(productOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
